# @time     :2022/2/19
# @Author   :Simple
# @FileName :driver
import os
import subprocess
import time

from appium import webdriver

from config import APPIUM_LOG, BASE_DIR
from util.device import check_device
from util.logger import log as logger
from util.port import check_port, release_port
from util.yaml import get_base_caps


class BaseDriver:
    """
    公共的base_driver类
    """

    def __init__(self, device_info, host="127.0.0.1"):
        self.device_info = device_info
        self.host = host

    def start_appium(self):
        """
        启动appium服务，并且输出appium日志
        :return:
        """

        port = int(self.device_info["server_port"])
        while not check_port(self.host, port):
            release_port(port)
            time.sleep(2)
        start_appium = f"appium -p {port} -bp {port + 1}"
        logger.info(f"start appium server: {start_appium}")
        appium_log_name = time.strftime("%Y_%m_%d_%H_%M_%S") + "-" + str(self.device_info['server_port'])
        out_path = os.path.join(APPIUM_LOG, appium_log_name + ".log")
        subprocess.Popen(start_appium, shell=True, stdout=open(out_path, 'a'), stderr=subprocess.STDOUT)
        time.sleep(2)

    def get_driver(self):
        """
        获取driver对象
        :return:
        """
        base_caps = get_base_caps()
        print(self.device_info.get('device_name'))
        if check_device(self.device_info['device_name']) == "ios":
            desired_caps = base_caps['iosCaps']
        else:
            desired_caps = base_caps['androidCaps']
            # web页面需要chrome driver
            driver_path = os.path.join(BASE_DIR, "/driver/chromedriver52")
            desired_caps["chromedriverExecutable"] = driver_path
            # desired_caps["systemPort"] = self.device_info["system_port"]
            # if self.device_info["platform_version"] < '7':
            #     desired_caps["automationName"] = 'uiautomator2'

        desired_caps["deviceName"] = self.device_info["device_name"]

        if self.device_info.get('udid'):
            desired_caps["udid"] = self.device_info["udid"]

        if self.device_info.get('platform_version'):
            desired_caps["platformVersion"] = self.device_info["platform_version"]

        logger.info(f'http://{self.host}:{self.device_info["server_port"]}/wd/hub')
        logger.info(f"desired_caps:{desired_caps}")
        driver = webdriver.Remote(f'http://{self.host}:{self.device_info["server_port"]}/wd/hub', desired_caps)
        return driver

    def close_appium(self):
        """
        关闭appoium服务
        :return:
        """
        release_port(self.device_info['server_port'])
